#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <string.h>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
  umask(0);
  //先让不同的进程看到同一份资源
  //创建管道
  int pipefd[2];
  int ret = pipe(pipefd);
  //int ret = pipe2(pipefd, 0);
  if(ret == -1)
  {
    std::cout << "pipe error" << errno << " : " << strerror(errno) << std::endl;
  }
  //创建子进程
  pid_t pid = fork();
  assert(pid >= 0);
  if(pid == 0)
  {
    //子进程
    //关闭不需要的fd
    close(pipefd[1]);
    //开始通信
    //int cnt = 0;
    while(1)
    {
      char buffer[1024];
      int n = read(pipefd[0], buffer, sizeof(buffer) - 1);
      if(n > 0)
      {
        buffer[n] = '\0';
        std::cout << "i get message : " << buffer << std::endl;
      }
      else{
        std::cout << "read error" << std::endl;
        break;
      }
    }

    close(pipefd[0]);
    exit(0);
  }
  //父进程
 //关闭不需要的fd
 close(pipefd[0]);
 int cnt = 1;
 while(1)
 {
   char ch[] = "i am father";
   write(pipefd[1], ch, sizeof(ch));
   std::cout << "这是我发的第 " << cnt++ << "条消息" <<std::endl;
  
   sleep(1);
 }

 close(pipefd[1]);

  return 0;
}
